import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import type { RootState } from '..'
import type { ApiError } from '../types'

const baseQuery = fetchBaseQuery({
  baseUrl: import.meta.env.VITE_API_URL,
  prepareHeaders: (headers, { getState }) => {
    const token = (getState() as RootState).app.auth.token
    if (token) {
      headers.set('Authorization', `Bearer ${token}`)
    }
    return headers
  },
  credentials: 'include',
})

const baseQueryWithReauth = async (args: any, api: any, extraOptions: any) => {
  let result = await baseQuery(args, api, extraOptions)

  if (result.error && (result.error as ApiError).status === 401) {
    // 尝试刷新令牌
    const refreshResult = await baseQuery(
      { url: '/auth/refresh', method: 'POST' },
      api,
      extraOptions
    )

    if (refreshResult.data) {
      // 存储新令牌
      api.dispatch({ type: 'app/setAuth', payload: refreshResult.data })
      // 重试原始请求
      result = await baseQuery(args, api, extraOptions)
    } else {
      // 刷新失败，登出用户
      api.dispatch({ type: 'app/logout' })
    }
  }

  return result
}

export const api = createApi({
  reducerPath: 'api',
  baseQuery: baseQueryWithReauth,
  tagTypes: [
    'Article',
    'Comment',
    'Category',
    'Tag',
    'User',
    'Setting',
    'Log',
    'Stats',
    'Search',
    'Notification',
  ],
  endpoints: () => ({}),
})

export const enhancedApi = api.enhanceEndpoints({
  addTagTypes: [
    'Article',
    'Comment',
    'Category',
    'Tag',
    'User',
    'Setting',
    'Log',
    'Stats',
    'Search',
    'Notification',
  ],
}) 